package cc.z8g.browser.search.suggestions

import cc.z8g.browser.core.BrowserConst
import cc.z8g.browser.database.SearchSuggestion
import org.xmlpull.v1.XmlPullParser
import java.io.InputStream

/**
 * Search suggestions provider for Google search engine.
 */
class GoogleSuggestionsModel : BaseSuggestionsModel() {

    // https://suggestqueries.google.com/complete/search?output=toolbar&hl={language}&q={query}
    override fun createQueryUrl(word: String): String {
        return "https://suggestqueries.google.com/complete/search?output=toolbar&hl=" + language + "&q=" + word
    }

    @Throws(Exception::class)
    override fun parseResults(bodyStream: InputStream): List<SearchSuggestion> {
        parser.setInput(bodyStream, BrowserConst.UTF8)

        val suggestions = mutableListOf<SearchSuggestion>()
        var eventType = parser.eventType
        while (eventType != XmlPullParser.END_DOCUMENT) {
            if (eventType == XmlPullParser.START_TAG && "suggestion" == parser.name) {
                val suggestion = parser.getAttributeValue(null, "data")
                suggestions.add(SearchSuggestion("$suggestionStr \"$suggestion\"", suggestion))
            }
            eventType = parser.next()
        }

        return suggestions
    }
}
